package com.charles.utils;


import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.annotation.ExcelProperty;
import com.charles.constants.EasyExcelConstants;
import com.charles.view.EasyExcelView;
import org.springframework.web.servlet.ModelAndView;

import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class EasyExcelUtils {

    /**
     * 导出excel
     *
     * @param title      文件标题
     * @param clazz      实体类型
     * @param exportList 导出数据
     * @param <T>
     * @return
     */
    public static <T> ModelAndView export(String title, String sheetName, Class<T> clazz, List<T> exportList) {
        ModelAndView mv = new ModelAndView(new EasyExcelView());
        mv.addObject(EasyExcelConstants.FILE_NAME, title);
        mv.addObject(EasyExcelConstants.SHEET_NAME, sheetName);
        mv.addObject(EasyExcelConstants.CLASS, clazz);
        mv.addObject(EasyExcelConstants.DATA_LIST, exportList);
        return mv;
    }

    public static boolean validateHead(List<String> headValueList, @NotNull Class<?> clazz) {
        List<String> headModelList = getHeadModelList(clazz);
        return headValueList.toString().equals(headModelList.toString());
    }

    public static List<String> getHeadModelList(Class<?> clazz) {
        List<String> headModelList = new ArrayList<>();
        Arrays.stream(clazz.getDeclaredFields()).forEach(x -> {
            if (x.isAnnotationPresent(ExcelProperty.class)) {
                ExcelProperty annotation = x.getAnnotation(ExcelProperty.class);
                headModelList.add(String.join(StrUtil.COMMA, annotation.value()));
            }
        });
        return headModelList;
    }

}